package com.ch.light.web.service.impl;

import com.ch.light.core.IdGenerator;
import com.ch.light.core.util.DigestUtil;
import com.ch.light.core.util.RegexUtil;
import com.ch.light.mybatis.ParamFilter;
import com.ch.light.web.dao.UserRoleDao;
import com.ch.light.web.mapper.UserMapper;
import com.ch.light.web.model.User;
import com.ch.light.web.service.UserService;
import com.ch.light.web.util.UserContextUtil;
import com.ch.utils.CommonUtils;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getList(ParamFilter paramFilter) {
        int pageNum = paramFilter.getPage().getPageNo();
        int pageSize = paramFilter.getPage().getPageSize();
        PageHelper.startPage(pageNum, pageSize, true, false, false);
        Example example = new Example(User.class);
        Map<String, Object> param = paramFilter.getParam();
//        if(StringUtils.isEmpty())
        return userMapper.selectByExample(example);
    }

    @Override
    public void updateDefaultPwd(List<String> userIds) {
        checkArgument((userIds != null && userIds.size() > 0), "用户编号不能为空");
        List<User> records = Lists.newArrayList();
        for (String userId : userIds) {
            User user = getByUserId(userId);
            checkNotNull(user, "用户不存在");
            records.add(user);
        }

        String defaultPwd = DigestUtil.sha256().digest("123456");
        records.forEach(r -> {
            User user = new User();
            user.setPassword(defaultPwd);
            user.setUpdateAt(new Date());
            user.setUpdateBy(UserContextUtil.getUserId());
            userMapper.updateByPrimaryKeySelective(user);
        });
    }

    @Override
    public void update(User record) {
        checkNotNull(record, "用户不能为空");
        checkArgument(!Strings.isNullOrEmpty(record.getUsername()), "帐号名不能为空");
//        checkArgument(!Strings.isNullOrEmpty(record.getPassword()), "密码不能为空");
        checkArgument(!Strings.isNullOrEmpty(record.getMobile()), "手机号码不能为空");
//        checkNotNull(record.getIsLock(), "帐号名不能为空");
        checkArgument(RegexUtil.isMobile(record.getMobile()), "手机号码格式不正确");
        if (!Strings.isNullOrEmpty(record.getEmail())) {
            checkArgument(RegexUtil.isEmail(record.getEmail()), "邮箱格式不正确");
        }
        User user = getByUserId(record.getNo());
        checkNotNull(user, "用户信息不存在");
        /*String oldPwd = user.getPassword();
        if (user.getPassword().equals(oldPwd)) {
            record.setPassword(oldPwd);
        } else {
            record.setPassword(DigestUtil.sha256().digest(oldPwd));
        }*/
        record.setUpdateAt(new Date());
        record.setUpdateBy(UserContextUtil.getUserId());
        BeanUtils.copyProperties(record, user);
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    @Transactional
    public void add(User record) {
        checkNotNull(record, "用户不能为空");
        checkArgument(!Strings.isNullOrEmpty(record.getUsername()), "帐号名不能为空");
        checkArgument(!Strings.isNullOrEmpty(record.getPassword()), "密码不能为空");
        checkArgument(!Strings.isNullOrEmpty(record.getMobile()), "手机号码不能为空");
//        checkNotNull(record.getIsLock(), "帐号名不能为空");
        checkArgument(RegexUtil.isMobile(record.getMobile()), "手机号码格式不正确");
        if (!Strings.isNullOrEmpty(record.getEmail())) {
            checkArgument(RegexUtil.isEmail(record.getEmail()), "邮箱格式不正确");
        }

        User param = new User();
        param.setUsername(record.getUsername());
        User user = userMapper.selectOne(param);
        checkArgument(user == null, "用户已存在");
        String password = DigestUtil.sha256().digest(record.getPassword());
        record.setErrorCount(BigInteger.ZERO.intValue());
        String userId = IdGenerator.getInstance().nextId();
        record.setNo(userId);
        record.setPassword(password);
        userMapper.insertSelective(record);
    }

    @Override
    public void updatePwd(String originPwd, String confirmPwd, String newPwd) {
        checkArgument(!Strings.isNullOrEmpty(originPwd), "原密码不能为空");
        checkArgument(!Strings.isNullOrEmpty(confirmPwd), "确认密码不能为空");
        checkArgument(!Strings.isNullOrEmpty(newPwd), "新密码不能为空");
        checkArgument(confirmPwd.equals(newPwd), "新密码与确认密码不一致");

        String userId = UserContextUtil.getUserId();
        User user = getByUserId(userId);
        checkNotNull(user, "用户对象不存在");
        checkArgument(user.getPassword().equals(DigestUtil.sha256().digest(originPwd)), "原密码不正确");

        String newPassword = DigestUtil.sha256().digest(confirmPwd);

        User r = new User();
        r.setPassword(newPassword);
        r.setUpdateAt(new Date());
        r.setUpdateBy(UserContextUtil.getUserId());
        userMapper.updateByPrimaryKeySelective(r);
    }

    @Override
    public void delete(List<String> userIds) {
        checkArgument((userIds != null && userIds.size() > 0), "用户编号不能为空");
        for (String userId : userIds) {
            User r = new User();
            r.setNo(userId);
            userMapper.delete(r);
            userMapper.removeAssignRolesByUserId(userId);
        }
    }

    @Override
    public User getDetail(String userId) {
        checkArgument(!Strings.isNullOrEmpty(userId), "用户编号不能为空");
        return getByUserId(userId);
    }

    @Override
    public User getByUserId(String userId) {
        checkArgument(!Strings.isNullOrEmpty(userId), "用户编号不能为空");
        User param = new User();
        param.setNo(userId);
        return userMapper.selectOne(param);
    }

    @Override
    public List<String> getPermission(String username) {
        return userMapper.getPermissions(username);
    }

    @Override
    public User findByUsername(String username) {
        checkArgument(!Strings.isNullOrEmpty(username), "用户名不能为空");
        User param = new User();
        param.setUsername(username);
        return userMapper.selectOne(param);

    }

    @Override
    public void assignRoles(String userId, List<String> addRoleIds) {
        checkArgument(!Strings.isNullOrEmpty(userId), "用户编号不能为空");
        checkArgument(CommonUtils.isNotEmpty(addRoleIds), "角色编号不能为空");
        addRoleIds.forEach(r -> userMapper.assignRole(userId, r));

    }

    @Override
    public void reassignRoles(String userId, List<String> delRoleIds) {
        checkArgument(!Strings.isNullOrEmpty(userId), "用户编号不能为空");
        checkArgument(CommonUtils.isNotEmpty(delRoleIds), "角色编号不能为空");
        delRoleIds.forEach(r -> userMapper.reassignRole(userId, r));
    }

}
